<template>
  <div class="device-select">
    <div class="select">
      <a-popover placement="bottomLeft">
        <template slot="content">
          <div style="overflow: hidden">
            <div style="margin-bottom: 8px">
              <a-input-search
                :placeholder="$t('deviceSelect.inputKeyword')"
                style="width: 100%"
                v-model="key"
                @change="onSearch"
              />
            </div>
            <a-table
              :row-key="(record) => record.serialNumber"
              :loading="loading"
              :columns="columns"
              :pagination="false"
              :data-source="tableData"
              size="small"
              :rowSelection="{
                type: 'radio',
                selectedRowKeys,
                onChange: onSelectChange,
              }"
              :customRow="customRow"
            ></a-table>
            <div class="pagination">
              <a-pagination
                size="small"
                :total="pagination.totalCount"
                :show-total="(total) => $t('deviceSelect.count', { total })"
                :pageSize="pagination.pageSize"
                @change="pageChange"
              />
            </div>
          </div>
        </template>
        <div class="select-view">
          <span>{{ selectSn }}</span
          ><a-icon type="down" class="down" />
        </div>
      </a-popover>
    </div>
  </div>
</template>
<script>
import { requestHttp, maccApi } from '@utils/index';
import _ from 'lodash';
import { i18nRender } from '@/locales';
const columns = [
  {
    title: i18nRender('deviceSelect.SN'),
    dataIndex: 'serialNumber',
    key: 'serialNumber',
    align: 'center',
  },
  {
    title: i18nRender('deviceSelect.name'),
    dataIndex: 'aliasName',
    key: 'aliasName',
    align: 'center',
  },
  {
    title: 'MAC',
    dataIndex: 'mac',
    key: 'mac',
    align: 'center',
  },
  {
    title: 'IP',
    dataIndex: 'localIp',
    key: 'localIp',
    align: 'center',
  },
  {
    title: i18nRender('deviceSelect.model'),
    dataIndex: 'productClass',
    key: 'productClass',
    align: 'center',
  },
];
export default {
  name: 'RJDeviceSelect', //设备选择器
  props: {
    commonType: {
      type: Array,
      default: () => [],
    },
    groupId: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      selectSn: '',
      loading: false,
      pagination: {
        totalCount: 0,
        page: 1,
        pageSize: 10,
      },
      tableData: [],
      selectedRowKeys: [],
      columns,
      key: '',
    };
  },
  watch: {
    groupId() {
      this.selectSn = this.$t('deviceSelect.chooseDevice');
      this.key = '';
      this.pagination = {
        totalCount: 0,
        page: 1,
        pageSize: 10,
      };
      this.selectedRowKeys = [];
      this.getTableList();
    },
    selectedRowKeys: {
      handler(n) {
        this.$emit('deviceChange', n[0]);
      },
      deep: true,
    },
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectSn = `${selectedRows[0].serialNumber}(${
        selectedRows[0].name || '-'
      })`;
    },
    pageChange(page, pageSize) {
      this.pagination.page = page;
      this.pagination.pageSize = pageSize;
      this.getTableList();
    },
    onSearch: _.debounce(function () {
      this.getTableList();
    }, 500),
    async getTableList() {
      const api = `${maccApi.DEVICE_LIST_POST_API.replace(
        '{page}',
        this.pagination.page
      ).replace('{per_page}', this.pagination.pageSize)}`;
      const params = {
        commonType: this.commonType.join(),
        groupId: this.groupId,
      };
      if (this.key) {
        params.searchKey = _.trim(this.key);
      }
      this.loading = true;
      const {
        code,
        deviceList = [],
        totalCount = 0,
        msg = this.$t('deviceSelect.getListFail'),
      } = await requestHttp({
        api,
        method: 'POST',
        params,
      });
      this.loading = false;
      if (code == 0) {
        this.tableData = deviceList;
        if (this.selectedRowKeys.length == 0 && deviceList.length > 0) {
          this.selectSn = `${deviceList[0].serialNumber}(${
            deviceList[0].name || '-'
          })`;
          this.selectedRowKeys.push(deviceList[0].serialNumber);
        } else if (deviceList.length == 0 && this.selectedRowKeys.length == 0) {
          this.$emit('groupDeviceEmpty');
        }
        this.pagination.totalCount = totalCount;
      } else {
        this.$message.error(msg);
      }
    },
    customRow(record) {
      const self = this;
      return {
        on: {
          click: () => {
            self.selectedRowKeys = [record.serialNumber];
            self.selectSn = `${record.serialNumber}(${record.name || '-'})`;
            //self.selectedRowKeys = [record.serialNumber];
            //self.$emit('deviceChange', record.serialNumber);
          },
        },
      };
    },
  },
};
</script>
<style lang="less" scoped>
.device-select {
  display: inline-block;
  .select {
    border: 1px solid @component-border;
    .border-radius;
    .select-view {
      padding: 0 12px;
      min-width: 230px;
      display: flex;
      height: 30px;
      justify-content: space-between;
      align-items: center;
      span {
        height: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        line-height: 32px;
        margin-right: 12px;
      }
      .down {
        color: @text-placeholder;
      }
    }
  }
}
.pagination {
  text-align: right;
  margin-top: 8px;
}
</style>
